<?php
/**
 * Copyright (c) 2020
 * 摘    要：
 * 作    者：san
 * 修改日期：2020.04.17
 */

namespace App\Service;

use App\Model\Permission;
use Donjan\Permission\PermissionRegistrar;
use ErrorException;
use Exception;
use Hyperf\Database\Model\Builder;
use Hyperf\Database\Model\Collection;
use Hyperf\Database\Model\Model;
use Hyperf\Utils\ApplicationContext;

class PermissionService extends BaseService
{
    /**
     * PermissionService constructor.
     */
    public function __construct()
    {
        parent::__construct();

        $this->redis = redis();
    }

    /**
     * 树形列表
     */
    public function tree()
    {
        $result = Permission::getMenuList();
        return $this->_handleRolePermission($result);
    }

    /**
     * 权限处理
     *
     * @param $permission
     * @return array
     */
    private function _handleRolePermission($permission)
    {
        if ($permission) {
            foreach ($permission as $key => $value) {
                $permission[$key]['type_name'] = $value['type'] == 1 ? '菜单' : '按钮';
                $permission[$key]['child']     = $this->_handleRolePermission($value['child']);
            }
        }
        return $permission;
    }

    /**
     * 获取顶级权限
     */
    public function top()
    {
        $result = Permission::query()->where('parent_id', 0)->get()->toArray();

        array_unshift($result, [
            'id'           => 0,
            'display_name' => '顶级权限',
        ]);

        return $result;
    }

    /**
     * 新增
     *
     * @param $data
     * @throws ErrorException
     */
    public function add($data)
    {
        //删除缓存
        ApplicationContext::getContainer()->get(PermissionRegistrar::class)->forgetCachedPermissions();

        $data['guard_name'] = 'web';
        $data['url']        = '';

        $this->_checkNameExits($data['name']);

        $ret = Permission::create($data);

        if (!$ret) {
            throw new ErrorException(t('message.12002'));
        }
    }

    /**
     * @param $data
     * @throws ErrorException
     */
    public function edit($data)
    {
        $id = $data['id'];

        $detail = $this->_checkExits($id);

        $this->_checkNameExits($data['name'], $id);

        $ret = $detail->where('id', $id)->update($data);

        if (!$ret) {
            throw new ErrorException(t('message.12002'));
        }

        //删除缓存
        ApplicationContext::getContainer()->get(PermissionRegistrar::class)->forgetCachedPermissions();
    }

    /**
     * @param $id
     * @throws ErrorException
     * @throws Exception
     */
    public function delete($id)
    {
        $detail = $this->_checkExits($id);

        $ret = $detail->delete();

        if (!$ret) {
            throw new ErrorException(t('message.12002'));
        }

        //删除缓存
        ApplicationContext::getContainer()->get(PermissionRegistrar::class)->forgetCachedPermissions();
    }


    /**
     * @param $id
     * @throws ErrorException
     * @return Builder|Builder[]|Collection|Model|null
     */
    private function _checkExits($id)
    {
        $detail = Permission::query()->find($id);

        if (!$detail) throw new ErrorException(t('message.12057'));

        return $detail;
    }

    /**
     * 检测权限名称是否唯一
     *
     * @param $name
     * @param int $id
     * @throws ErrorException
     */
    private function _checkNameExits($name, $id = 0)
    {
        $query = Permission::query()
            ->where('name', $name);

        if ($id) {
            $query = $query->where('id', '<>', $id);
        }

        $hasOne = $query->first();

        if ($hasOne) {
            throw new ErrorException(t('message.12056'));
        }
    }
}
